package com.agileai.portal.extend.uui;

import java.io.InputStream;
import java.io.StringWriter;
import java.io.Writer;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import com.agileai.common.AppConfig;
import com.agileai.hotweb.common.BeanFactory;
import com.agileai.hotweb.common.StringTemplateLoader;
import com.agileai.portal.wsclient.uui.UserSync;
import com.agileai.portal.wsclient.uui.UserSync_Service;
import com.agileai.util.CryptionUtil;
import com.agileai.util.IOUtil;
import com.sun.xml.internal.messaging.saaj.util.ByteOutputStream;

import freemarker.template.Configuration;
import freemarker.template.ObjectWrapper;
import freemarker.template.Template;

public class UserSyncHelper {
	private static boolean Inited = false;
	private static boolean EnableUserInfoSync = false; 
	private static String UserSyncServiceURL = null;
	private static String TokenSecurityKey = null;
	private static UserSync UserSyncInstance = null;
	private static AppConfig AppConfig = null;
	
	public static boolean isEnableUserInfoSync(){
		init();
		return EnableUserInfoSync;
	}
	
	private static String getUserSyncServiceURL(){
		init();
		return UserSyncServiceURL;
	}
	
	private static String getTokenSecurityKey(){
		init();
		return TokenSecurityKey;
	}
	
	private static void init(){
		if (!Inited){
			AppConfig = BeanFactory.instance().getAppConfig();
			TokenSecurityKey = AppConfig.getConfig("UnifiedUserIntegrateConfig", "TokenSecurityKey");
			UserSyncServiceURL = AppConfig.getConfig("UnifiedUserIntegrateConfig", "UserSyncServiceURL");
			EnableUserInfoSync = AppConfig.getBoolConfig("UnifiedUserIntegrateConfig", "EnableUserInfoSync");
			Inited = true;
		}
	}
	
	public static UserSync getUserSyncService() throws MalformedURLException{
		if (UserSyncInstance == null){
			URL url = new URL(getUserSyncServiceURL());
			UserSync_Service userSyncService = new UserSync_Service(url);
			UserSyncInstance = userSyncService.getUserSyncPort();				
		}
		return UserSyncInstance;
	}
	
	public static String genTokenId(String operationName){
		return CryptionUtil.encryption(operationName,getTokenSecurityKey());
	}
	
	public static String genMaskedMail(String mail){
		String result = "";
		int index = mail.indexOf("@");
		String front = mail.substring(0,index);
		String back = mail.substring(index+1,mail.length());
		
		int frontMaskLength = front.length() * 1/3;
		int backMaskLength = back.length() * 1/3;
		
		result = front.substring(0,front.length()-frontMaskLength)+getMaskChars(frontMaskLength)+"@"+getMaskChars(backMaskLength)+back.substring(backMaskLength);
		
		return result;
	}
	private static String getMaskChars(int length){
		StringBuffer result = new StringBuffer();
		for (int i=0;i < length;i++){
			result.append("*");
		}
		return result.toString();
	}
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static String createFindPwdMailContent(String userCode,String tokenId){
		String result = null;
		try {
			InputStream inputStream = UserSyncHelper.class.getResourceAsStream("FindPwdNotify.ftl");
			ByteOutputStream byteOutputStream = new ByteOutputStream();
			IOUtil.copyAndCloseInput(inputStream, byteOutputStream);
			String templContent = new String(byteOutputStream.getBytes(),"UTF-8");
			
			String activeURL = AppConfig.getConfig("UnifiedUserIntegrateConfig", "ResetPasswordURLPrefix");
			
			String activeLink = activeURL + "&userId="+userCode+"&tokenId="+tokenId;
			HashMap model = new HashMap();
			model.put("userName", userCode);
			model.put("resetPasswordLink", activeLink);
			
			StringWriter writer = new StringWriter();
			generate(templContent, model, writer);
			result = writer.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static String createRegistryMailContent(String userCode,String tokenId){
		String result = null;
		try {
			InputStream inputStream = UserSyncHelper.class.getResourceAsStream("RegistryNotify.ftl");
			ByteOutputStream byteOutputStream = new ByteOutputStream();
			IOUtil.copyAndCloseInput(inputStream, byteOutputStream);
			String templContent = new String(byteOutputStream.getBytes(),"UTF-8");
			
			String activeURL = AppConfig.getConfig("UnifiedUserIntegrateConfig", "UserActiveURLPrefix");
			
			String activeLink = activeURL + "&userId="+userCode+"&tokenId="+tokenId;
			HashMap model = new HashMap();
			model.put("userName", userCode);
			model.put("activeLink", activeLink);
			
			StringWriter writer = new StringWriter();
			generate(templContent, model, writer);
			result = writer.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	private static void generate(String templContent,Object model,Writer writer,String encoding) {
		try {
        	Configuration cfg = new Configuration();
        	cfg.setTemplateLoader(new StringTemplateLoader(templContent));  
        	cfg.setEncoding(Locale.getDefault(), encoding);
            cfg.setObjectWrapper(ObjectWrapper.BEANS_WRAPPER);
        	Template temp = cfg.getTemplate("");
        	temp.setEncoding(encoding);
            Map root = new HashMap();
            root.put("model",model);
            temp.process(root, writer);
            writer.flush();
            writer.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private static void generate(String templContent,Object model,Writer writer) {
		generate(templContent, model, writer,"UTF-8");
	}	
}